package com.loadmore.stepcount

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import java.util.*


/**
 *@author sunleilei
 *@date 2018/7/26
 *@time 16:14
 *
 */
object StepAlarmManager {
    fun init(context: Context) {
        setTimeAlarm(context)
        setClearAlarm(context)

    }

    fun setClearAlarm(context: Context) {
        var alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val zeroIntent = Intent(context, AlarmTimeReceiver::class.java)
        zeroIntent.action = AlarmActions.zero_alarm
        var zeroAlarmIntent = PendingIntent.getBroadcast(context, 1, zeroIntent, 0)

        // Set the alarm to start at 23:55
        val zeroCalendar = Calendar.getInstance()
        zeroCalendar.set(Calendar.HOUR_OF_DAY, 23)
        zeroCalendar.set(Calendar.MINUTE, 55)
        zeroCalendar.set(Calendar.MILLISECOND,0)
        zeroCalendar.set(Calendar.SECOND,0)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, zeroCalendar.timeInMillis-System.currentTimeMillis(),AlarmManager.INTERVAL_DAY, zeroAlarmIntent)
        }
    }
    fun setTimeAlarm(context: Context) {
        var alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, AlarmTimeReceiver::class.java)
        intent.action = AlarmActions.upload_step_count
        var alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0)
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.MINUTE, 5)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 5*60*1000, 1000*60*5,alarmIntent)
        }


    }
    fun stopAlarm(context: Context) {
        var alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, AlarmTimeReceiver::class.java)
        intent.action = AlarmActions.upload_step_count

        var alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0)
        alarmManager.cancel(alarmIntent)


        val zeroIntent = Intent(context, AlarmTimeReceiver::class.java)
        zeroIntent.action = AlarmActions.zero_alarm
        var zeroAlarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0)
        alarmManager.cancel(zeroAlarmIntent)
    }
}